import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import 'package:sonora/bloc/medal/sj_medal_bloc.dart';
import 'package:sonora/bloc/medal/sj_medal_event.dart';
import 'package:sonora/bloc/medal/sj_medal_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_storage_utils.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/dialog/sj_medal_obtain_dailog.dart';
import 'package:sonora/views/dialog/sj_privacy_dailog.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';
import 'package:sonora/views/sj_main_screen.dart';
import 'package:sonora/views/sj_root_provider.dart';

@RoutePage()
class SjMedalPage extends StatefulWidget {
  @override
  State<SjMedalPage> createState() => _SjMedalPageState();
}

class _SjMedalPageState extends State<SjMedalPage> {
  late SjMedalBloc _medalBloc;

  @override
  void initState() {
    super.initState();
    _medalBloc = getit<SjMedalBloc>();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showDialog();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true, // 使内容延伸到导航
        appBar: SjAppbar(
          backgroundColor: Colors.transparent, // 设置导航栏背景为透明
          elevation: 0, // 去除导航栏阴影
        ),
        body: BlocProvider<SjMedalBloc>.value(
            value: _medalBloc
              ..add(const SjMedalEventLoadedUserInfo())
              ..add(const SjMedalEventLoadedMedal()),
            child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/profile_bg_me.png'),
                    fit: BoxFit.cover,
                  ),
                ),
                child: SafeArea(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    child: Column(children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            child: Column(
                              children: [
                                BlocBuilder<SjMedalBloc, SjMedalState>(
                                    builder: (bContext, state) {
                                  return Container(
                                    width: 80, // Diameter (2 * radius) = 2 * 15
                                    height:
                                        80, // Diameter (2 * radius) = 2 * 15
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      image: DecorationImage(
                                        image: NetworkImage(state
                                                .userInfoData?.avatarUrl ??
                                            ''), // Replace with your avatar image URL
                                        fit: BoxFit.cover,
                                      ),
                                      border: Border.all(
                                        color: Colors.black, // Border color
                                        width: 2, // Border width
                                      ),
                                      boxShadow: [
                                        BoxShadow(
                                          color: SjColors
                                              .themeColor, // Shadow color and opacity
                                          offset: Offset(
                                              1, 1), // Shadow offset (x, y)
                                        ),
                                      ],
                                    ),
                                  );
                                }),
                                SizedBox(
                                  height: 6,
                                ),
                                BlocBuilder<SjMedalBloc, SjMedalState>(
                                    builder: (bContext, state) {
                                  return Text(
                                      state.userInfoData?.nickname ?? '',
                                      style: SjTextStyle.customFontBlack20);
                                })
                              ],
                            ),
                          ),
                        ],
                      ),
                      Container(
                          padding: EdgeInsets.symmetric(vertical: 12),
                          decoration: BoxDecoration(
                            color: SjColors.whiteColor,
                            border: Border.all(
                              color: Colors.black, // Border color
                              width: 2, // Border width
                            ),
                            borderRadius:
                                BorderRadius.all(Radius.circular(12.0)),
                          ),
                          child: BlocBuilder<SjMedalBloc, SjMedalState>(
                              builder: (bContext, state) {
                            return Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Container(
                                        padding:
                                            EdgeInsets.fromLTRB(17, 5, 17, 2),
                                        decoration: BoxDecoration(
                                          color: SjColors.themeAColor,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10.0)),
                                        ),
                                        child: Row(children: [
                                          Text(
                                            'Click on the medal style above to equip',
                                            style:
                                                SjTextStyle.customFontTheme12,
                                          )
                                        ]),
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: 8,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_sm_1.png'),
                                          (state.medal1IsObtain != null &&
                                                  state.medal1IsObtain == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_sm.png'),
                                        ],
                                      ),
                                      SizedBox(
                                        width: 21,
                                      ),
                                      Image.asset(
                                          'assets/images/medal_upgrade_icon.png'),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_bg_y_1.png'),
                                          (state.medal1IsUpgrade != null &&
                                                  state.medal1IsUpgrade == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_bg.png'),
                                        ],
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: 8,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_sm_2.png'),
                                          (state.medal2IsObtain != null &&
                                                  state.medal2IsObtain == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_sm.png'),
                                        ],
                                      ),
                                      SizedBox(
                                        width: 21,
                                      ),
                                      Image.asset(
                                          'assets/images/medal_upgrade_icon.png'),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_bg_y_2.png'),
                                          (state.medal2IsUpgrade != null &&
                                                  state.medal2IsUpgrade == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_bg.png'),
                                        ],
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: 8,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_sm_3.png'),
                                          (state.medal3IsObtain != null &&
                                                  state.medal3IsObtain == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_sm.png'),
                                        ],
                                      ),
                                      SizedBox(
                                        width: 21,
                                      ),
                                      Image.asset(
                                          'assets/images/medal_upgrade_icon.png'),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Stack(
                                        children: [
                                          Image.asset(
                                              'assets/images/xz_bg_y_3.png'),
                                          (state.medal3IsUpgrade != null &&
                                                  state.medal3IsUpgrade == true)
                                              ? SizedBox()
                                              : Image.asset(
                                                  'assets/images/xz_lock_bg.png'),
                                        ],
                                      )
                                    ],
                                  ),
                                ]);
                          })),
                      Expanded(child: BlocBuilder<SjMedalBloc, SjMedalState>(
                          builder: (bContext, state) {
                        int count = 0;
                        if (state.medalList != null) {
                          count = state.medalList!.length;
                        }
                        return ListView.builder(
                            padding: EdgeInsets.only(top: 8),
                            shrinkWrap: true,
                            itemBuilder: ((context, index) {
                              var medal = state.medalList![index];
                              return Padding(
                                padding: EdgeInsets.only(bottom: 8),
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 5, horizontal: 12),
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter,
                                      colors: [
                                        Color(0x4DFFFFFF),
                                        Color(0xFFFFFFFF)
                                      ],
                                    ),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(12.0)),
                                  ),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        child: Row(
                                          children: [
                                            Stack(
                                              children: [
                                                Image.asset(medal.assetPath ??
                                                    'assets/images/xz_sm_1.png'),
                                                (medal.isObtain != null &&
                                                        medal.isObtain == true)
                                                    ? SizedBox()
                                                    : Image.asset(
                                                        'assets/images/xz_lock_sm.png'),
                                              ],
                                            ),
                                            SizedBox(
                                              width: 8,
                                            ),
                                            Column(
                                              children: [
                                                Text(medal.title ?? '',
                                                    style: SjTextStyle
                                                        .customFontTheme14),
                                                Text(medal.dec ?? '',
                                                    style: SjTextStyle
                                                        .customFontTheme10),
                                              ],
                                            )
                                          ],
                                        ),
                                      ),
                                      (medal.isObtain != null &&
                                              medal.isObtain == true &&
                                              medal.isUpgrade != null &&
                                              medal.isUpgrade == true)
                                          ? SizedBox()
                                          : Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  9, 6, 9, 3),
                                              decoration: BoxDecoration(
                                                  color: SjColors.blackColor,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(18))),
                                              child: InkWell(
                                                  onTap: () {
                                                    if (index == 0 ||
                                                        (medal.isObtain !=
                                                                null &&
                                                            medal.isObtain ==
                                                                true)) {
                                                      context.router
                                                          .push(
                                                              const SjMedalStoreRoute())
                                                          .then((value) {
                                                        _medalBloc
                                                          ..add(SjMedalEvent
                                                              .loadedUserInfo())
                                                          ..add(SjMedalEvent
                                                              .loadedMedalData());
                                                      });
                                                    } else if (index == 1) {
                                                      context.router.push(SjArticlePublishRoute()).then((value) {
                                                        _medalBloc
                                                          ..add(SjMedalEvent
                                                              .loadedUserInfo())
                                                          ..add(SjMedalEvent
                                                              .loadedMedalData());
                                                      });
                                                    } else if (index == 2) {
                                                       Provider.of<SjRootProvider>(context, listen: false).changeIndex(0);
                                                    }
                                                  },
                                                  child: Text(
                                                    (medal.isObtain != null &&
                                                            medal.isObtain ==
                                                                true)
                                                        ? 'Upgrade'
                                                        : 'To Obtain',
                                                    style: SjTextStyle
                                                        .customFontTheme12,
                                                  )),
                                            )
                                    ],
                                  ),
                                ),
                              );
                            }),
                            itemCount: count);
                      }))
                    ]),
                  ),
                ))));
  }

  void _showDialog() async {
    BuildContext mContext = context;
    bool? first = await SjStorageUtils.getMedalPageNotFirst();
    if (first != null && first == true) {
      return;
    }
    if (!mounted) return;
    showDialog(
        barrierDismissible: false,
        context: mContext,
        builder: (BuildContext context) {
          return SjMedalObtainDialog(
            assetPath: 'assets/images/xz_bg_1.png',
            content:
                'Welcome to the Medal Backpack page for the first time. We have prepared a medal for you so that you can have a better experience.',
            onAgree: () {
              _medalBloc.add(SjMedalEvent.obtain1Medal());
            },
            onCancel: () {},
          );
        });
  }
}
